package com.hspedu.hspliving.commodity.service.impl;

import com.hspedu.hspliving.commodity.dao.BrandDao;
import com.hspedu.hspliving.commodity.dao.CategoryDao;
import com.hspedu.hspliving.commodity.entity.BrandEntity;
import com.hspedu.hspliving.commodity.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.common.utils.PageUtils;
import com.hspedu.common.utils.Query;

import com.hspedu.hspliving.commodity.dao.CategoryBrandRelationDao;
import com.hspedu.hspliving.commodity.entity.CategoryBrandRelationEntity;
import com.hspedu.hspliving.commodity.service.CategoryBrandRelationService;

import javax.xml.ws.Action;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAll(CategoryBrandRelationEntity categoryBrandRelation) {
        CategoryEntity categoryEntity = categoryDao.selectById(categoryBrandRelation.getCategoryId());
        BrandEntity brandEntity = brandDao.selectById(categoryBrandRelation.getBrandId());

        categoryBrandRelation.setCategoryName(categoryEntity.getName());
        categoryBrandRelation.setBrandName(brandEntity.getName());

        this.save(categoryBrandRelation);
    }

    @Override
    public List<BrandEntity> getBrandByCategoryId(Long categoryId) {
        //通过categoryId获取brandRelation
        List<CategoryBrandRelationEntity> brandRelation = categoryBrandRelationDao.selectList(
                new QueryWrapper<CategoryBrandRelationEntity>().eq("category_id", categoryId));

        //防止空id,selectBatch报错
        if(brandRelation.size()==0){
            return Collections.emptyList();
        }

        //通过brandId获取brandEntity
        List<Long> brandIds = brandRelation.stream().map((item) -> {
            return item.getBrandId();}).collect(Collectors.toList());
        return brandDao.selectBatchIds(brandIds);
    }
}
